<template>
  <el-main>
    <div id="kinds" @click='chooseKind($event)'>
      <el-tag
        :key="index"
        v-for="(kind, index) in goodList"
        closable
        :disable-transitions="false"
        @close="deleteKind(index, kind.id)"
        :class='["bag-tag", currentKindIndex===index? "focus":""]'
        :data-index='index'
        >
        {{kind.name}}
      </el-tag>
      <el-input
        class="input-new-tag"
        v-if="inputVisible"
        v-model="inputValue"
        ref="saveTagInput"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      >
      </el-input>
      <el-button v-else class="button-new-tag" @click="showInput">{{Text.addKindText}}</el-button>
      <!-- <el-radio-group v-model="radio2">
        <el-radio :label="index" v-for='(kind, index) in goodList' :key='index'>{{kind.name}}</el-radio>
      </el-radio-group> -->
    </div>
    <el-button id="addGoods" @click="addGoods()" class="button-new-tag">{{Text.addGoodText}}</el-button>
    <el-table
      ref="multipleTable"
      :data="goodList.length? goodList[currentKindIndex].goods:[]"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        min-width="50">
      </el-table-column>
      <el-table-column
        type="index"
        min-width="50">
      </el-table-column>
      <el-table-column
        prop="name"
        :label="$t('goodColumn.name')"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="price"
        :label="$t('goodColumn.price')"
        min-width="50">
      </el-table-column>
      <el-table-column
        prop="count"
        :label="$t('goodColumn.count')"
        min-width="50">
      </el-table-column>
      <el-table-column
        prop="sales"
        :label="$t('goodColumn.sales')"
        min-width="50">
      </el-table-column>
      <el-table-column fixed="right" :label="$t(Text.op)" width="150">
        <template slot-scope="scope">
          <!-- <el-button @click="lookupGood(scope.row)" type="text" size="small">查看</el-button> -->
          <el-button @click="editGood(scope.row, scope.$index)" type="text" size="small">{{$t(Text.edit)}}</el-button>
          <el-button @click="deleteGood(scope.row, scope.$index)" type="text" size="small">{{$t(Text.delete)}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="Contents Of Goods" :close-on-click-modal='false' @close='handleDialogClose' :visible.sync="dialogFormVisible">
      <el-form :model="goodInDialog">
        <el-form-item :label="$t('goodColumn.name')" :label-width="formLabelWidth">
          <el-input v-model="goodInDialog.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('goodColumn.price')" :label-width="formLabelWidth">
          <el-col :span="11">
            <el-input v-model="priceNumDia" placeholder=""></el-input>
            <el-input style="display:none" v-model="goodInDialog.price" auto-complete="off"></el-input>
          </el-col>
          <el-col :span="11">
            <el-select style="margin-left:10px" v-model="nowCurrency" :placeholder="$t(Text.chooseCurrency)">
              <el-option
                v-for="item in currencies"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('goodColumn.count')" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodInDialog.count" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('goodColumn.picurl')" :label-width="formLabelWidth">
          <img id="goodpic" :src="goodInDialog.picurl" alt="">
          <uploader @recieveNewImg='recieveNewImg'></uploader>
        </el-form-item>
        <el-form-item :label="$t('goodColumn.description')" :label-width="formLabelWidth">
          <el-input v-model="goodInDialog.description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('goodColumn.detail')" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="goodInDialog.detail" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">{{$t(Text.cancel)}}</el-button>
        <!-- <el-button type="primary" @click="dialogFormVisible = false" >确 定</el-button> -->
        <el-button @click="saveOrInsert">{{$t(Text.save)}}</el-button>
      </div>
    </el-dialog>
  </el-main>
</template>
<script>
import uploader from '@/components/uploader/uploader'
import api from '@/API/index.js'
import * as _ from 'lodash'

export default {
  name: 'goods',
  data() {
    return {
      Text: {
        addKindText: this.$t('goods.addKindText'),
        addGoodText: this.$t('goods.addGoodText'),
        save: this.$t('goods.save'),
        cancel: this.$t('goods.cancel'),
        chooseCurrency: this.$t('goods.chooseCurrency'),
        edit: this.$t('goods.edit'),
        delete: this.$t('goods.delete'),
        op: this.$t('goods.op')
      },
      shopId: window.localStorage.shopId,
      goodList: [],
      goodInDialog: {},
      formLabelWidth: '120px',
      dialogFormVisible: false,
      operationType: null, // 1->编辑 2->新增
      // 控制当前选中的商品类型
      currentKindIndex: 0,
      currentGoodIndex: 0,
      // 控制添加标签
      inputVisible: false,
      inputValue: '',
      // 选择币种的下拉列表
      currencies: [
        {
          label: '欧元',
          value: '€'
        },
        {
          label: '美元',
          value: '$'
        },
        {
          label: '人民币',
          value: '￥'
        }
      ],
      nowCurrency: '',
      priceNumDia: null
    }
  },
  computed: {},
  created() {
    this.getGoodsByShopId(this.shopId)
  },
  watch: {
    nowCurrency() {
      this.goodInDialog.price = this.nowCurrency + this.priceNumDia
    },
    priceNumDia() {
      this.goodInDialog.price = this.nowCurrency + this.priceNumDia
    }
  },
  mounted() {},
  components: {
    uploader
  },
  methods: {
    // dialog取消或者关闭的回调
    handleDialogClose() {
      this.dialogFormVisible = false
      this.recoverDialog()
    },
    // 初始化dialog，在编辑或者新建商品保存之后
    recoverDialog() {
      // 保存完成后，把dialog中的数据初始化
      this.goodInDialog = {}
      this.nowCurrency = ''
      this.priceNumDia = null
    },
    // 从uploader组件获取头像url的函数，uploader中调用
    recieveNewImg(url) {
      this.goodInDialog.picurl = url
    },
    // TODO: table 多选，批量删除还没做
    toggleSelection(rows) {
      if (rows) {
        // eslint-disable-next-line
        rows.forEach((row, index) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    editGood(row, index) {
      this.operationType = 1
      // 深度复制
      this.goodInDialog = _.cloneDeep(row)
      // eslint-disable-next-line
      this.nowCurrency = this.goodInDialog.price[0]
      this.priceNumDia = this.goodInDialog.price.substr(1, this.goodInDialog.price.length - 1)
      this.currentGoodIndex = index
      // this.goodInDialog = row
      this.dialogFormVisible = true
    },
    addGoods() {
      this.operationType = 2
      const newGood = {
        name: '',
        price: '',
        picurl: '',
        description: '',
        count: 0,
        sales: 0,
        detail: '',
        kindId: this.goodList[this.currentKindIndex].id
      }
      this.goodInDialog = newGood
      this.dialogFormVisible = true
    },
    // 点击dialog中的保存按钮触发
    saveOrInsert() {
      api.UPSERT(this.goodInDialog).then(({ data }) => {
        this.$message(data.msg)
        if (data.status !== 200) {
          return
        }
        // operationType 判断是编辑还是新建商品
        if (this.operationType === 1) {
          // TODO: 提示编辑成功
          this.$set(this.goodList[this.currentKindIndex].goods, this.currentGoodIndex, this.goodInDialog)
          // this.goodList[this.currentKindIndex].goods[this.currentGoodIndex] = this.goodInDialog
        } else if (this.operationType === 2) {
          this.getGoodsByShopId(this.shopId)
        }
        this.recoverDialog()
        this.dialogFormVisible = false
      })
    },
    deleteGood(row, index) {
      this.$confirm('确定要删除？')
        .then(() => {
          const goods = []
          goods.push({ id: row.id })
          api.DELETE_GOODS(goods).then(({ data }) => {
            if (data.status === 200) {
              this.goodList[this.currentKindIndex].goods.splice(index, 1)
            }
          })
        })
        .catch(() => {})
    },
    chooseKind(event) {
      // eslint-disable-next-line
      if (event.target.classList.contains('el-tag')) {
        this.currentKindIndex = parseInt(event.target.dataset.index, 10)
      }
    },
    // e-tag
    deleteKind(kindIndex, kindId) {
      this.$confirm('确定要删除该分类？')
        .then(() => {
          const kinds = []
          kinds.push({ id: kindId })
          api.DELETE_KINDS(kinds).then(({ data }) => {
            if (data.status === 200) {
              if (kindIndex <= this.currentKindIndex) {
                this.currentKindIndex = this.currentKindIndex - 1 < 0 ? 0 : this.currentKindIndex - 1
              }
              this.goodList.splice(kindIndex, 1)
            }
          })
        })
        .catch(() => {})
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      if (!this.inputValue) {
        return
      }
      const kinds = [{ name: this.inputValue }]
      api.ADD_KINDS(kinds).then(({ data }) => {
        if (data.status === 200) {
          // eslint-disable-next-line
          // _.forEach(data.data.kinds, (item, index) => {
          //   // eslint-disable-next-line
          //   item.goods = {}
          //   this.goodList.push(item)
          // })
          this.goodList = _.concat(this.goodList, data.data.kinds)
        }
      })
      this.inputVisible = false
      this.inputValue = ''
    },
    // 调用api
    getGoodsByShopId(shopId) {
      api.GET_GOODS_BY_SHOPID({ shopId }).then(({ data }) => {
        if (data.status === 200) {
          this.goodList = data.data.goods
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
#goodpic {
  height: 100px;
  width: 100px;
}
#addGoods {
  margin: 20px 0 15px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.el-tag {
  cursor: pointer;
}
.el-tag.focus {
  background-color: rgba(57, 230, 0, 0.27);
}
.button-new-tag {
  margin-left: 10px;
  height: 32px !important;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.bag-tag {
  height: 32px !important;
  line-height: 30px;
}
</style>
